package com.example.aaa_viewpager;

import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.conn.params.ConnConnectionParamBean;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.example.aaa_viewpager.entity.User;
import com.example.aaa_viewpager.service.UserDAO;
import com.example.bb_serch.R;

import android.app.IntentService;
import android.content.Context;
import android.content.Intent;
import android.content.Loader.OnLoadCompleteListener;
import android.database.Cursor;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

public class fragment2 extends Fragment {

	// UI
	private TextView tv;
	private ListView top20_list;
	private Button btn_show;

	// 取得JSON attr
	private JSONArray array;
	private String[] num;
	private String[] view_name;
	private String[] view_vote;
	private String[] view_url;
	
	
	//simpleAdapter使用
	ArrayList<HashMap<String, String>> list;

	private static final String TAG = "HTTPGET";
	

	public void onActivityCreated(Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);
		initView();
		// 採用HttpGet進行連線，並取得網頁內容getEntity

		initHandler();
	}

	@Override
	public View onCreateView(LayoutInflater inflater,
			@Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		return inflater.inflate(R.layout.view2, container, false);
	}

	private void initHandler() {
		btn_show.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) 
			{
				
				try
				{
					ArrayAdapter<String> adapter = new ArrayAdapter<String>(
							getActivity(),
							android.R.layout.simple_expandable_list_item_1,
							view_name);
					top20_list.setAdapter(adapter);
				}
				catch(Exception ex)
				{
					Toast.makeText(getActivity(), "請連接網路!!!", Toast.LENGTH_LONG).show();
				}
				
				
			
				
				
				
//				//simpleAdapter使用 有問題閃退!!
//				for(int i=0;i<view_name.length;i++)
//				{
//					HashMap<String, String> item = new HashMap<String, String>();
//					item.put("cate_name", view_name[i]);
//					item.put("votes",view_vote[i]);
//					list.add(item);
//				}
//					
//					SimpleAdapter adapter = new SimpleAdapter(
//							getActivity(),
//							list,
//							android.R.layout.simple_list_item_2,
//							new String[]{"cate_name","votes"},
//							new int[]{android.R.id.text1,android.R.id.text2});
//					top20_list.setAdapter(adapter);
					
			}
		});
		top20_list.setOnItemLongClickListener(new OnItemLongClickListener() {

			@Override
			public boolean onItemLongClick(AdapterView<?> parent, View view,
					int position, long id)
			{
				String text = "第"+num[position]+"名"+"\n"+"本周得票數 : " + view_vote[position];
				Toast.makeText(getActivity(), text, Toast.LENGTH_SHORT).show();
				return true;
			}
		});
		
		top20_list.setOnItemClickListener(new OnItemClickListener() 
		{

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) 
			{
//				String text = "第"+num[position]+"名"+"\n"+"得票數 : " + view_vote[position];
//				Toast.makeText(getActivity(), text, Toast.LENGTH_SHORT).show();
				
				
				Uri uri = Uri.parse(view_url[position]);
				Intent it = new Intent(Intent.ACTION_VIEW , uri);
				startActivity(it);
				
				
			}
		});

	}

	private void initView() 
	{
		
		tv = (TextView) getActivity().findViewById(R.id.top20_title);
		top20_list = (ListView) getActivity().findViewById(R.id.top20_list);
		btn_show = (Button) getActivity().findViewById(R.id.showData);
		
////		//判斷是否有網路，若無...btn_show無法按
////		try
////		{
////			ConnectivityManager cm = (ConnectivityManager)getActivity().getSystemService(Context.CONNECTIVITY_SERVICE);
////			NetworkInfo info = cm.getActiveNetworkInfo();
////			if(info.isAvailable() & info.isConnectedOrConnecting())
////			{
////				btn_show.setEnabled(true);
////				//Toast.makeText(getActivity(), "有網路", Toast.LENGTH_LONG).show();
////			}
////			else
////			{
////				btn_show.setEnabled(false);
////				//Toast.makeText(getActivity(), "無網路", Toast.LENGTH_LONG).show();
////				
////			}
//				
//		}
//		catch(Exception ex)
//		{
//			
//		}
		
		
		// 建立多執行緒進行網路Server API串接的資料傳輸與讀取
		new Thread(new Runnable() {

			@Override
			public void run() {
				String str = "";
				Log.i("111","111");
				HttpClient httpClient = new DefaultHttpClient();
				Log.i("222","222");
				// API串接的url路徑
				String url = ("https://googledrive.com/host/0B7ezv9C5CRz_NGlXUWNydUE3Wk0");
				Log.i("333","333");
				try {
					HttpGet mHttpGet = new HttpGet(url);
					HttpResponse response = httpClient.execute(mHttpGet);

					// API的回傳文字，格式為JSON格式
					str = EntityUtils.toString(response.getEntity(), "utf-8");
					array = new JSONArray(str);
					parseJSON(array);
					Log.i("sssss", "sssss");

				} catch (Exception ex) {
					//Log.e(TAG, ex.getMessage());
					Log.i("444","444");
				}

			}

		}).start();

	}

	protected void parseJSON(final JSONArray content) {
		getActivity().runOnUiThread(new Runnable() {

			@Override
			public void run() {
				// 解析JSON
				try {
						num = new String[content.length()];
						view_name = new String[content.length()];
						view_vote = new String[content.length()];
						view_url = new String[content.length()];
						for (int i = 0; i < content.length(); i++) {

						JSONObject obj = array.getJSONObject(i);

						Log.e("id", obj.getString("id"));
						Log.e("cate_name", obj.getString("cate_name"));
						Log.e("votes", obj.getString("votes"));
						Log.e("url", obj.getString("url"));

						// 將以下JSON的值透過迴圈 寫到對應的陣列裡
						num[i] = obj.getString("id");
						view_name[i] = obj.getString("cate_name");
						view_vote[i] = obj.getString("votes");
						view_url[i] = obj.getString("url");
						
					}

				} catch (JSONException e) {

					e.printStackTrace();

				}
			}

		});

	}
	

}
